package com.itheima.health.mobile.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.mobile.vo.SmsLoginParam;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
public class LoginController {
    @DubboReference
    private SmsService smsService;
    @DubboReference
    private MemberService memberService;
    @PostMapping("smsLogin")
    public Result login(Integer count, @RequestBody SmsLoginParam smsLoginParam){
        log.info("[登录请求]data:{}", smsLoginParam);
        if (count == 0) {
            return new Result(false, "请先获取验证码");
        }
        if (smsLoginParam.getTelephone() == null || smsLoginParam.getValidateCode() == null) {
            return new Result(false, MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        Integer checkValidateCode = smsService.checkValidateCode("MOBILE_SIGNIN", smsLoginParam.getTelephone(), smsLoginParam.getValidateCode(), count);
        if (checkValidateCode == 1) {
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        } else if (checkValidateCode == -1) {
            return new Result(false, "验证码超时已失效");
        }

        //查看手机号是不是会员 不是的话存进去 member
        Member member = new Member();
        member.setPhoneNumber(smsLoginParam.getTelephone());
        Member member1 = memberService.createOrUpdate(member);

        log.info("[登录成功]会员id为：{}", member1.getId());
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }
}
